/*
 * Jalon 4 Tampon
 * See "ICR - 04 - La communication inter-processus - version 0.8.pdf"
 * This is pretty much like a mailbox the processes use to communicate
 * with each other.
 * get and put methods do not need to be mutually exclusive as
 * ArrayList objects are thread safe since Java 1.2
 */
package client;

import common.Helper;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 *
 */
public class Buffer
{
    private static int MAX_BUFFER_SIZE = 3;

    private Semaphore slotAvailableSemaphore = new Semaphore(MAX_BUFFER_SIZE);
    private Semaphore nbValuesSemaphore = new Semaphore(0);

    /**
     * ArrayList are thread safe since Java 1.2
     */
    private ArrayList<BufferMessage> arrayList = new ArrayList<BufferMessage>();

    /**
     * A mutual exclusion between get and put is not required as
     * we're using an ArrayList which is thread safe since Java 1.2
     * @return
     */
    public BufferMessage get()
    {
        try
        {
            nbValuesSemaphore.acquire();
        } catch (InterruptedException ex)
        {
            Logger.getLogger(Buffer.class.getName()).log(Level.SEVERE, null, ex);
        }
        BufferMessage val = arrayList.get(0);
        arrayList.remove(0);
        // notifyAll();

        // we now have one more slot available
        slotAvailableSemaphore.release();
        Thread.currentThread().getName();
        return val;
    }

    public void put(BufferMessage val)
    {
        try
        {
            slotAvailableSemaphore.acquire();
        } catch (InterruptedException ex)
        {
            Logger.getLogger(Buffer.class.getName()).log(Level.SEVERE, null, ex);
        }
        arrayList.add(val);
        nbValuesSemaphore.release();
        // notifyAll();
    }

    public int getNumberMessageInBuffer(){
        return arrayList.size();
    }
}
